package org.ciallo.simplemusicplayer.dialog;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.SongDetailOptionsAdapter;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.util.Constants;
import org.ciallo.simplemusicplayer.util.RingtoneUtil;
import org.ciallo.simplemusicplayer.util.TimeUtil;
import org.ciallo.simplemusicplayer.viewmodel.FavoritesViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Jukomu
 * @Description: 从底部弹出的对话框，显示当前播放歌曲的详细信息和更多操作选项
 * @Package: org.ciallo.simplemusicplayer.dialog
 * @Project: SimpleMusicPlayer
 * @name: PlayerSongDetailsDialogFragment
 * @Date: 2025/5/29-04:51
 * @Filename: PlayerSongDetailsDialogFragment
 */
public class PlayerSongDetailsDialogFragment extends BottomSheetDialogFragment {
    public static final String TAG = "PlayerSongDetailsDialog";

    private TextView tvSongTitle, tvArtistName, tvAlbumName;
    private RelativeLayout layoutTitle, layoutArtist, layoutAlbum;
    private RecyclerView recyclerViewOptions;
    private SongDetailOptionsAdapter optionsAdapter;

    private SharedViewModel sharedViewModel;
    private FavoritesViewModel favoritesViewModel; // 用于收藏功能
    private Song currentSong;

    // 操作项的ID常量
    private static final int OPTION_ID_FAVORITE = 1;
    private static final int OPTION_ID_ADD_TO_PLAYLIST = 2;
    static final int OPTION_ID_SET_RINGTONE = 3;
    private static final int OPTION_ID_SONG_INFO = 4;
    static final int OPTION_ID_SHARE_SONG = 5;
    public static final int OPTION_ID_CLOSE = 6;


    public static PlayerSongDetailsDialogFragment newInstance() {
        return new PlayerSongDetailsDialogFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        // favoritesViewModel = new ViewModelProvider(requireActivity()).get(FavoritesViewModel.class); // <--- 需要创建 FavoritesViewModel
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_player_song_details_options, null);
        dialog.setContentView(view);

        // 初始化视图
        tvSongTitle = view.findViewById(R.id.textView_dialog_details_song_title);
        tvArtistName = view.findViewById(R.id.textView_dialog_details_artist_name);
        tvAlbumName = view.findViewById(R.id.textView_dialog_details_album_name);
        layoutTitle = view.findViewById(R.id.layout_details_title);
        layoutArtist = view.findViewById(R.id.layout_details_artist);
        layoutAlbum = view.findViewById(R.id.layout_details_album);
        recyclerViewOptions = view.findViewById(R.id.recyclerView_dialog_song_options);

        favoritesViewModel = new ViewModelProvider(requireActivity()).get(FavoritesViewModel.class);

        setupRecyclerView();
        observePlaybackInfo();

        // 设置点击事件
        layoutTitle.setOnClickListener(v -> copyToClipboard("歌曲名称", currentSong != null ? currentSong.getTitle() : ""));
        layoutArtist.setOnClickListener(v -> {
//            if (currentSong != null && currentSong.getArtistIdRoom() != -1 && currentSong.getArtistName() != null) { // 假设 artistId=-1 表示未知
//                Intent intent = new Intent(getActivity(), ArtistSongsActivity.class);
//                intent.putExtra(ArtistSongsActivity.EXTRA_ARTIST_ID, currentSong.getArtistIdRoom());
//                intent.putExtra(ArtistSongsActivity.EXTRA_ARTIST_NAME, currentSong.getArtistName());
//                startActivity(intent);
//                dismiss();
//            } else {
//                Toast.makeText(getContext(), "歌手信息不可用", Toast.LENGTH_SHORT).show();
//            }
        });
        layoutAlbum.setOnClickListener(v -> {
//            if (currentSong != null && currentSong.getAlbumIdRoom() != -1 && currentSong.getAlbumName() != null) { // 假设 albumId=-1 表示未知
//                Intent intent = new Intent(getActivity(), AlbumSongsActivity.class);
//                intent.putExtra(AlbumSongsActivity.EXTRA_ALBUM_ID, currentSong.getAlbumIdRoom());
//                intent.putExtra(AlbumSongsActivity.EXTRA_ALBUM_NAME, currentSong.getAlbumName());
//                intent.putExtra(AlbumSongsActivity.EXTRA_ALBUM_ART_URI, currentSong.getAlbumArtUri());
//                startActivity(intent);
//                dismiss();
//            } else {
//                Toast.makeText(getContext(), "专辑信息不可用", Toast.LENGTH_SHORT).show();
//            }
        });


        // 设置 BottomSheetBehavior
        BottomSheetBehavior<?> bottomSheetBehavior = dialog.getBehavior();
        if (bottomSheetBehavior != null) {
            // 设置最大高度为屏幕的70%-80%
            // bottomSheetBehavior.setPeekHeight((int) (getResources().getDisplayMetrics().heightPixels * 0.75));
            // 让其可以完全展开
            bottomSheetBehavior.setSkipCollapsed(true); // 跳过折叠状态，直接到展开或隐藏
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            // 动态设置最大高度，以避免内容过少时也占据很高空间
            view.post(() -> {
                int maxHeight = (int) (getResources().getDisplayMetrics().heightPixels * 0.75);
                if (view.getHeight() > maxHeight) {
                    ViewGroup.LayoutParams params = view.getLayoutParams();
                    params.height = maxHeight;
                    view.setLayoutParams(params);
                }
            });
        }
        return dialog;
    }

    private void setupRecyclerView() {
        List<SongDetailOptionsAdapter.OptionItem> options = new ArrayList<>();
        // 后续会根据收藏状态动态更新 "收藏" 项的文本
        options.add(new SongDetailOptionsAdapter.OptionItem(OPTION_ID_FAVORITE, getString(R.string.song_option_favorite), R.drawable.ic_favorite_border, R.drawable.ic_chevron_right));
        options.add(new SongDetailOptionsAdapter.OptionItem(OPTION_ID_ADD_TO_PLAYLIST, getString(R.string.player_add_to_playlist), R.drawable.ic_playlist_add, R.drawable.ic_chevron_right)); // 需要 ic_playlist_add
        options.add(new SongDetailOptionsAdapter.OptionItem(OPTION_ID_SET_RINGTONE, getString(R.string.player_set_as_ringtone), R.drawable.ic_ringtone, R.drawable.ic_chevron_right)); // 需要 ic_ringtone
        options.add(new SongDetailOptionsAdapter.OptionItem(OPTION_ID_SONG_INFO, "歌曲信息", R.drawable.ic_info_about, R.drawable.ic_chevron_right));
        options.add(new SongDetailOptionsAdapter.OptionItem(OPTION_ID_SHARE_SONG, "分享", R.drawable.ic_share, R.drawable.ic_chevron_right)); // 复用分享图标
        options.add(new SongDetailOptionsAdapter.OptionItem(OPTION_ID_CLOSE, "关闭", R.drawable.ic_close_small, 0)); // 关闭按钮通常不需要右箭头

        AtomicBoolean shouldDismiss = new AtomicBoolean(true); // 默认操作后关闭对话框
        optionsAdapter = new SongDetailOptionsAdapter(options, item -> {
            if (currentSong == null && item.id != OPTION_ID_CLOSE) {
                Toast.makeText(getContext(), "当前无歌曲", Toast.LENGTH_SHORT).show();
                return;
            }
            switch (item.id) {
                case OPTION_ID_FAVORITE:
                    if (currentSong != null && favoritesViewModel != null) {
                        // 触发操作，UI 的更新将由 observePlaybackInfo -> updateFavoriteOptionText 中的 LiveData 观察者处理
                        favoritesViewModel.isFavorite(currentSong.getId()).observe(getViewLifecycleOwner(), new Observer<Boolean>() {
                            @Override
                            public void onChanged(Boolean isCurrentlyFavorite) {
                                // 移除观察者，避免重复触发或内存泄漏 (只操作一次)
                                favoritesViewModel.isFavorite(currentSong.getId()).removeObserver(this);

                                if (isCurrentlyFavorite != null) {
                                    if (isCurrentlyFavorite) {
                                        favoritesViewModel.removeFromFavorites(currentSong.getId());
                                        Toast.makeText(getContext(), "已取消收藏", Toast.LENGTH_SHORT).show();
                                    } else {
                                        favoritesViewModel.addToFavorites(currentSong.getId());
                                        Toast.makeText(getContext(), "已收藏", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    // 如果初始状态是null，默认为未收藏，则添加
                                    favoritesViewModel.addToFavorites(currentSong.getId());
                                    Toast.makeText(getContext(), "已收藏 (状态初始化)", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                    break;
                case OPTION_ID_ADD_TO_PLAYLIST:
                    if (currentSong != null && getParentFragmentManager() != null) {
                        AddToPlaylistDialogFragment.newInstance(currentSong.getId())
                                .show(getParentFragmentManager(), AddToPlaylistDialogFragment.TAG);
                    } else {
                        Toast.makeText(getContext(), "无法添加到歌单 (歌曲信息缺失)", Toast.LENGTH_SHORT).show();
                    }
                    shouldDismiss.set(false); // 对话框不立即关闭，等待用户在 AddToPlaylistDialog 中操作
                    break;
                case OPTION_ID_SET_RINGTONE:
                    if (currentSong != null) showSetAsRingtoneDialog(currentSong);
                    break;
                case OPTION_ID_SONG_INFO:
                    if (currentSong != null) showSongInfoDialog(currentSong);
                    break;
                case OPTION_ID_SHARE_SONG:
                    if (currentSong != null) shareCurrentSongInternal(currentSong);
                    dismissAfterDelay();
                    break;
                case OPTION_ID_CLOSE:
                    dismiss();
                    break;
            }
        });
        if (shouldDismiss.get()) {
            dismiss();
        }

        recyclerViewOptions.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewOptions.setAdapter(optionsAdapter);
    }

    /**
     * 当播放信息（尤其是当前歌曲）改变时，更新对话框内的歌曲详情和收藏按钮状态。
     */
    private void observePlaybackInfo() {
        sharedViewModel.playbackInfo.observe(getViewLifecycleOwner(), playbackInfo -> {
            if (playbackInfo != null && playbackInfo.song != null) {
                currentSong = playbackInfo.song;
                updateSongDetailsUI(currentSong);
                updateFavoriteOptionText(currentSong.getId()); // 更新收藏按钮文本和图标
            } else {
                currentSong = null;
                updateSongDetailsUI(null);
                // 如果没有歌曲，收藏选项可能需要禁用或显示默认
                updateFavoriteOptionText(Constants.INVALID_INDEX); // 用无效ID更新为默认状态
            }
        });
    }

    private void updateSongDetailsUI(@Nullable Song song) {
        if (song != null) {
            tvSongTitle.setText(song.getTitle());
            tvArtistName.setText(song.getArtistName());
            tvAlbumName.setText(song.getAlbumName());
        } else {
            tvSongTitle.setText("无歌曲");
            tvArtistName.setText("");
            tvAlbumName.setText("");
        }
    }

    /**
     * 根据当前歌曲的收藏状态更新“收藏/取消收藏”选项的文本和图标。
     * @param songId 当前歌曲的ID。
     */
    private void updateFavoriteOptionText(long songId) {
        if (favoritesViewModel == null || optionsAdapter == null) {
            Timber.w("FavoritesViewModel or OptionsAdapter not initialized in updateFavoriteOptionText.");
            return;
        }
        // 找到列表中的收藏选项
        SongDetailOptionsAdapter.OptionItem favItem = null;
        int favItemPosition = -1;
        for (int i = 0; i < optionsAdapter.getItemCount(); i++) {
            SongDetailOptionsAdapter.OptionItem currentItem = optionsAdapter.optionItems.get(i);
            if (currentItem.id == OPTION_ID_FAVORITE) {
                favItem = currentItem;
                favItemPosition = i;
                break;
            }
        }
        if (favItem == null) {
            Timber.e("Favorite option item not found in adapter.");
            return;
        }

        final SongDetailOptionsAdapter.OptionItem finalFavItem = favItem; // 在lambda中需要final或effectively final
        final int finalFavItemPosition = favItemPosition;

        if (songId == Constants.INVALID_INDEX) { // 没有歌曲，显示默认未收藏状态
            finalFavItem.setText(getString(R.string.song_option_favorite));
            finalFavItem.iconResId = R.drawable.ic_favorite_border;
            if (finalFavItemPosition != -1) optionsAdapter.notifyItemChanged(finalFavItemPosition);
            return;
        }

        // 观察收藏状态 LiveData
        favoritesViewModel.isFavorite(songId).observe(getViewLifecycleOwner(), isFavorite -> {
            if (isFavorite != null) { // 确保 LiveData 返回了非null值
                finalFavItem.setText(isFavorite ? getString(R.string.song_option_unfavorite) : getString(R.string.song_option_favorite));
                finalFavItem.iconResId = isFavorite ? R.drawable.ic_favorite_filled : R.drawable.ic_favorite_border;
            } else {
                // LiveData 初始可能为 null，或歌曲ID无效时（虽然上面处理了 INVALID_INDEX）
                finalFavItem.setText(getString(R.string.song_option_favorite)); // 默认文本
                finalFavItem.iconResId = R.drawable.ic_favorite_border;       // 默认图标
            }
            if (finalFavItemPosition != -1) { // 确保位置有效
                optionsAdapter.notifyItemChanged(finalFavItemPosition);
            }
        });
    }


    private void copyToClipboard(String label, String text) {
        if (getContext() == null || text == null || text.isEmpty()) return;
        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(label, text);
        if (clipboard != null) {
            clipboard.setPrimaryClip(clip);
            Toast.makeText(getContext(), label + "已复制到剪贴板", Toast.LENGTH_SHORT).show();
        }
    }

    private void showSetAsRingtoneDialog(Song songToSet) {
        if (getContext() == null || songToSet == null) return;
        final String[] types = {"来电铃声", "通知铃声", "闹钟铃声"};
        final int[] ringtoneTypes = {
                android.media.RingtoneManager.TYPE_RINGTONE,
                android.media.RingtoneManager.TYPE_NOTIFICATION,
                android.media.RingtoneManager.TYPE_ALARM
        };

        new AlertDialog.Builder(requireContext())
                .setTitle("设为铃声")
                .setItems(types, (dialog, which) -> {
                    if (RingtoneUtil.canWriteSettings(requireContext())) {
                        RingtoneUtil.setRingtone(requireContext(), songToSet, ringtoneTypes[which]);
                    } else {
                        RingtoneUtil.requestWriteSettingsPermission(requireContext());
                    }
                    dismiss(); // 操作后关闭底部弹窗
                })
                .setNegativeButton(R.string.cancel, (d, w) -> dismiss())
                .show();
    }

    private void showSongInfoDialog(Song song) {
        if (getContext() == null || song == null) return;
        StringBuilder infoBuilder = new StringBuilder();
        infoBuilder.append("标题: ").append(song.getTitle()).append("\n");
        infoBuilder.append("歌手: ").append(song.getArtistName()).append("\n");
        infoBuilder.append("专辑: ").append(song.getAlbumName()).append("\n");
        infoBuilder.append("时长: ").append(TimeUtil.formatDuration(song.getDuration())).append("\n");
        infoBuilder.append("路径: ").append(song.getPath()).append("\n");
        infoBuilder.append("大小: ").append(formatFileSize(song.getSize())).append("\n");
        if (song.getMimeType() != null) infoBuilder.append("格式: ").append(song.getMimeType()).append("\n");
        if (song.getYear() > 0) infoBuilder.append("年份: ").append(song.getYear()).append("\n");

        new AlertDialog.Builder(requireContext())
                .setTitle("歌曲信息")
                .setMessage(infoBuilder.toString())
                .setPositiveButton(R.string.ok, null)
                .show();
        // dismiss(); // 查看信息后通常不关闭底部弹窗，让用户可以继续其他操作
    }

    // 辅助方法：格式化文件大小
    public static String formatFileSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return String.format(Locale.getDefault(), "%.1f %s", size / Math.pow(1024, digitGroups), units[digitGroups]);
    }


    private void shareCurrentSongInternal(Song song) {
        if (getContext() == null || song == null) return;
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        String shareBody = "我正在听: " + song.getTitle();
        if (song.getArtistName() != null && !song.getArtistName().isEmpty() && !Constants.UNKNOWN_STRING.equals(song.getArtistName())) {
            shareBody += " - " + song.getArtistName();
        }
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(shareIntent, "分享到..."));
        dismiss();
    }

    // 添加一个延迟关闭的方法，以便 Toast 可以显示完毕
    private void dismissAfterDelay() {
        new Handler(Looper.getMainLooper()).postDelayed(this::dismissAllowingStateLoss, 300);
    }


    @Override
    public void onDestroyView() {
        // SharedViewModel 会管理 PlayerController 的生命周期
        super.onDestroyView();
    }
}
